// @ts-ignore
import ExcelJS from "exceljs";
// @ts-ignore
import { saveAs } from "file-saver";

// 类型定义
interface ScheduleEntry {
  [key: string]: any;
  time: string;
}

interface Person {
  name: string;
  weeks: number[];
}

const weeksToRanges = (weeks: number[]): string => {
  if (!weeks.length) return "";
  const sorted = [...weeks].sort((a, b) => a - b);
  const ranges: string[] = [];
  let start = sorted[0];
  let end = start;

  for (let i = 1; i < sorted.length; i++) {
    if (sorted[i] === end + 1) {
      end = sorted[i];
    } else {
      ranges.push(start === end ? `${start}` : `${start}-${end}`);
      start = end = sorted[i];
    }
  }
  ranges.push(start === end ? `${start}` : `${start}-${end}`);
  return ranges.join(",");
};

const generateExcel = async (data: ScheduleEntry[], startWeek: number, endWeek: number, orgName: string) => {
  // 创建工作簿
  const workbook = new ExcelJS.Workbook();
  const worksheet = workbook.addWorksheet("无课表");

  // 设置表头样式
  worksheet.columns = [
    {
      header: "",
      width: 20,
      style: { font: { bold: true }, alignment: { vertical: "middle", horizontal: "center" } }
    },
    { header: "周一", width: 20 },
    { header: "周二", width: 20 },
    { header: "周三", width: 20 },
    { header: "周四", width: 20 },
    { header: "周五", width: 20 },
    { header: "周六", width: 20 },
    { header: "周日", width: 20 }
  ];

  // 设置表头样式
  worksheet.getRow(1).eachCell((cell: ExcelJS.Cell) => {
    cell.font = { bold: true, size: 14 };
    cell.alignment = { vertical: "middle", horizontal: "center" };
  });

  // 添加数据行
  data.forEach(entry => {
    const row = worksheet.addRow([entry.time]);

    // 设置时间段列样式
    row.getCell(1).font = { bold: true };
    row.getCell(1).alignment = { vertical: "middle", horizontal: "center", wrapText: true };

    // 处理每一天数据
    ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"].forEach((day, idx) => {
      const currentPeople: Person[] = entry[day] || [];
      const personWeeks = new Map(currentPeople.map(p => [p.name, new Set(p.weeks)]));

      const freePeople = Array.from(new Set(currentPeople.flatMap(p => p.name)))
        .sort()
        .map(name => {
          const hasWeeks = personWeeks.get(name) || new Set();
          const free = Array.from({ length: endWeek }, (_, i) => i + 1).filter(
            w => w >= startWeek && w <= endWeek && hasWeeks.has(w)
          );
          const ranges = weeksToRanges(free);
          if (ranges === "") {
            return "";
          } else if (ranges === `${startWeek}-${endWeek}`) {
            return name;
          } else {
            return `${name}(${ranges}周)`;
          }
        });

      const cell = row.getCell(idx + 2);
      cell.value = freePeople.join("\n");
      cell.alignment = {
        vertical: "middle",
        horizontal: "center",
        wrapText: true // 启用自动换行
      };
    });
  });
  // 获取全部名字
  const totalPeopleNames = data.flatMap(entry => {
    return Object.values(entry).flatMap((day: any) => {
      return Array.isArray(day) ? day.map((person: any) => person.name) : [];
    });
  });
  // 去重
  const uniquePeopleNames = [...new Set(totalPeopleNames)];
  // 在表头下方添加人数
  const peopleRow = worksheet.getRow(1);
  peopleRow.getCell(1).value = `总人数: ${uniquePeopleNames.length}`;
  peopleRow.getCell(1).font = { bold: true };
  peopleRow.getCell(1).alignment = { vertical: "middle", horizontal: "center" };

  // 生成文件
  const buffer = await workbook.xlsx.writeBuffer();
  const blob = new Blob([buffer], {
    type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
  });
  saveAs(blob, `${orgName}_${startWeek}-${endWeek}_无课表.xlsx`);
};

export default generateExcel;
